#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "protocolo.h"


/*Funcion para pasar de integer a string*/

char* itoa(int valor)
{
	char* string = malloc(sizeof(valor));
	int valorRetorno;

	valorRetorno = snprintf(string,32,"%d",valor);

	if(valorRetorno == -1) return(-1);

	return(string);
}

/*Compacta el mensaje*/

char *NIPC_Serialize(NIPC *nipc)
{
	char *result = malloc(sizeof(struct nodoNIPC));
	char *auxType = itoa(nipc->type);
	char *auxPayloadLength;
	int i = 0;

	auxPayloadLength = malloc(2);

	strcpy(auxPayloadLength,itoa(nipc->payloadLength));
	for(i=strlen(auxPayloadLength);i<=2;i++) strcat(auxPayloadLength,"\0");

	strcpy(result,"");
	strcat(result,auxType);
	strcat(result,"*");
	strcat(result,auxPayloadLength);
	strcat(result,"*");
	strcat(result,nipc->payload);

	free(auxPayloadLength);

	return result;
}

/*Descompacta el mensaje*/

NIPC *NIPC_Unserialize(char *input)
{
	NIPC *nipc = malloc(sizeof(struct nodoNIPC));
	char *auxType = malloc(4);
	char *auxPayloadLength = malloc(4);
	char *auxPayload = malloc(strlen(input));
	char *string = malloc(sizeof(input));
	int offset = 0;

	strcpy(string,input);

	auxType = strtok(string,"*");
	offset += strlen(auxType) + 1;
	memcpy(auxPayloadLength,input + offset,sizeof(input));
	auxPayloadLength = strtok(auxPayloadLength,"*");
	offset += strlen(auxPayloadLength) + 1;
	memcpy(auxPayload,input + offset,strlen(input) - offset);

	nipc->type = atoi(auxType);
	nipc->payloadLength = atoi(auxPayloadLength);
	nipc->payload = auxPayload;

	free(auxPayloadLength);

	return nipc;
}